const app = getApp();
const my = require('../../classes/lib/util.js');
const user = require('../../classes/application/user.js');
const address = require('../../classes/application/address.js');
Page({

  data: {
    themes: null,
    user : null,
    address : null,
    region: null,
    formValues : null,
    picker_text:'请选择',
    order_id:null,
  },
  onLoad: function (options) {
    this.setData({
      order_id: my.ival(options.order_id),
      themes : app.globalData.themes,
      user : app.globalData.userInfo,
      address: app.globalData.address,
    })
  },
  onShow: function () {
    var region = my.L("selected_region");
    if (region && region.province && region.province.region_name) {
      console.log("addr:onShow:selected_region not null");
      this.setData({
        region: region,
        picker_text: [region.province.region_name, region.city.region_name, region.district.region_name].join(','),
      });
    } else if (this.data.address && this.data.address.province) {
      console.log("addr:onShow:data.address not null");
      this.setData({
        picker_text: [this.data.address.province, this.data.address.city, this.data.address.district].join(','),
        region: {
          province: { region_name: this.data.address.province },
          city: { region_name: this.data.address.province },
          district: { region_name: this.data.address.district },
        }
      });
      console.log("addr:onShow:region:" + JSON.stringify(this.data.region));
    } else {
      this.setData({
        picker_text: '请选择',
      });      
    }
  },
  formSubmit: function (e) {
    this.setData({
      formValues: e.detail.value
    });
    console.log("addr:formSubmit=" +JSON.stringify(this.data.formValues));
    this.saveAddress();
  },
  doSelectRegion: function (e) {
    wx.navigateTo({
      url: '../region/region',
    });
  },
  saveAddress: function () {
    if (!this.data.formValues.consignee) {
      my.toast("请设置收货人");
      return;
    }
    if (!this.data.formValues.tel) {
      my.toast("请设置手机号码");
      return;
    }
    if (!this.data.region) {
      my.toast("请设置所在区域");
      return;
    }
    if (!this.data.formValues.address) {
      my.toast("请设置详细地址");
      return;
    }
    var that = this;
    address.save({
      openid: app.globalData.openid,
      address_id: (this.data.address) ? this.data.address.address_id:0,
      order_id: this.data.order_id,
      country: 1,
      province: this.data.region.province.region_id,
      city: this.data.region.city.region_id,
      district: this.data.region.district.region_id,
      consignee: this.data.formValues.consignee,
      address: this.data.formValues.address,
      zipcode: '000000',
      tel: this.data.formValues.tel,
      callback: function (data) {
       app.globalData.address = data;
       if(this.data.order_id>0){
         wx.navigateBack({
           delta:-1
         });
       }else{
         my.alert("更新成功");
       }
      }
    })
  },
})